﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Xml.Linq;
using System.Xml;
using System.Collections.Specialized;
using Microsoft.SharePoint.Navigation;
using SlamCms.Common;
using Slam.SharePoint;
using SlamCms.SharePoint.Core;
using System.Collections;
using System.IO;

namespace SlamCms.SharePoint.Migration
{
	public static class MigrationService
	{	
		public static void Import(string siteUrl, string filePath, bool includeContent, bool activateSlam)
		{
			FileInfo fileInfo = new FileInfo(filePath);

			XmlTextReader reader = new XmlTextReader(filePath);
			
			XDocument doc = XDocument.Load(reader);
			MigratableSite site = new MigratableSite();
			site.FromXml(doc.Element("Site"));
			using (SPSite siteCollection = new SPSite(siteUrl))
			{
				if(includeContent)
					siteCollection.Import(siteUrl.Replace(siteCollection.Url, "").TrimStart('/'), site, fileInfo.DirectoryName, activateSlam);
				else
					siteCollection.Import(siteUrl.Replace(siteCollection.Url, "").TrimStart('/'), site, "", activateSlam);
			}
		}

		public static void Import(string siteUrl, string filePath, bool includeContent, bool activateSlam, Action<string> logAction)
		{
			FileInfo fileInfo = new FileInfo(filePath);

			XmlTextReader reader = new XmlTextReader(filePath);

			XDocument doc = XDocument.Load(reader);
			MigratableSite site = new MigratableSite();
			site.FromXml(doc.Element("Site"));
			using (SPSite siteCollection = new SPSite(siteUrl))
			{
				if (includeContent)
					siteCollection.Import(siteUrl.Replace(siteCollection.Url, "").TrimStart('/'), site, fileInfo.DirectoryName, activateSlam, logAction);
				else
					siteCollection.Import(siteUrl.Replace(siteCollection.Url, "").TrimStart('/'), site, "", activateSlam);
			}
		}

		public static void Export(string siteUrl, string filePath, bool includeSubSites, bool includeContent)
		{
			FileInfo fileInfo = new FileInfo(filePath);
			using (var siteCollection = new SPSite(siteUrl))
			{
				using (var site = siteCollection.OpenWeb())
				{
					XElement node = site.Export(fileInfo.DirectoryName, true, includeContent).ToXml();
					var doc = new XDocument(node);
					var settings = new XmlWriterSettings();
					settings.Indent = true;
					settings.CloseOutput = true;
					var writer = XmlWriter.Create(filePath, settings);
					doc.Save(writer);
					writer.Flush();
					writer.Close();
				}
			}
		}
	}
}
